<script setup lang="ts">
defineOptions({
  name: "selfContainer"
});
import {
  getVmContainerDetail,
  vmLog,
  getVmPortPrice,
  getVmStatus,
  getContainerLog,
  addVmPort,
  getContainerList,
  getContainerPrice,
  pay_request,
  deleteConNet,
  DelHttp
} from "@/api/user";
import { changeInstancePasswordUser } from "@/api/server";
import { useRoute, useRouter } from "vue-router";
import { ElForm } from "element-plus";
import { statusMap, statusColor, vmStatus, vmStatusColor } from "@/utils/hide";
import { onMounted, ref, reactive } from "vue";
import { message } from "@/utils/message";
import { debounce } from "@pureadmin/utils";
import SetButton from "./components/SetButton.vue";
import VirtualWeb from "./components/VirtualWeb.vue";
import Snapshot from "./components/Snapshot.vue";
import RunLogs from "./components/RunLogs.vue";
import PayVolumes from "./components/PayVolumes.vue";

const route = useRoute();
const router = useRouter();
onMounted(async () => {
  // 虚拟机信息
  await getInfo();
  // 操作信息
  await getVmLog();
  // 获取虚拟机状态
  await getStatus();
  // 运行日志
  getContainerLog({
    container_id: route.query.container_id
  }).then(res => {
    if (res.data.data.data) {
      let logs = res.data.data.data.logs;
      run_logs.value = logs.split("\\r\\n");
      run_logs.value.pop();
      run_logs.value = run_logs.value.map(log => ({ log }));
    }
  });
  getWidth();
});
const run_logs = ref([]);
const container_state = ref();

// 链接端口号
const Vm_link = ref({
  node_port: ""
});
// 获取虚拟机信息
const getInfo = async () => {
  await getVmContainerDetail(route.query.container_id).then(res => {
    container_message.value = res.data.data;
    server.value = res.data.data.server;
    plan.value = res.data.data.plan;
    image.value = res.data.data.image;
    container_connect.value = res.data.data.port_forwards;
    volumes.value = res.data.data.volumes;
    password_text.value = res.data.data.password;
    Vm_link.value = res.data.data.port_forwards.find(
      item => item.internal_port == 3389
    );
    console.log("密码", Vm_link.value);
  });
};
// 虚拟机密码
const password_text = ref("");
const SetPassWord = async id => {
  await changeInstancePasswordUser(id, { password: password_text.value }).then(
    async res => {
      console.log("修改密码", res);
      message(res.data.data, { type: "success" });
      await getInfo();
    }
  );
};

// 获取虚拟机状态
const Vm_State = ref("");
const getStatus = async () => {
  let res = await getVmStatus(route.query.container_id);
  Vm_State.value = res.data.data.data.state;
};

// 获取虚拟机操作日志
const getVmLog = async () => {
  vmLog({ ...logPagin }).then(res => {
    containers_log.value = res.data.data;
    logTotal.value = res.data.count;
  });
};
//操作日志分页
const logTotal = ref(10);
const logPagin = reactive({
  count: 10,
  page: 1,
  id: route.query.container_id
});
const handleCurrentPageChange = async newPage => {
  logPagin.page = newPage;
  getVmLog();
};
const handlePageSizeChange = async newSize => {
  logPagin.count = newSize;
  getVmLog();
};

const container_message = ref({});
const server = ref({});
const plan = ref({});
const image = ref({});
const containers_log = ref([]);
const container_connect = ref([]);
const volumes = ref([]);
//响应式
const widthcolumn = ref(4);
const getWidth = () => {
  let screenWidth = window.innerWidth;
  if (screenWidth < 768) {
    widthcolumn.value = 2;
  } else {
    widthcolumn.value = 4;
  }
};

// 购买端口
const paylist = reactive({
  pay_type: "3",
  port: "",
  instance_id: route.query.container_id
});
const pay_src = ref("");
const pay_url = ref("");
const pay_dialog = ref(false);
//支付
const formRef = ref<InstanceType<typeof ElForm>>();
const payloading = ref(false);
const topay = async () => {
  payloading.value = true;
  formRef.value?.validate(async valid => {
    if (valid) {
      await addVmPort(paylist).then(res => {
        console.log(res);
        if (res.data.code == 200) {
          pay_request({
            pay_type: res.data.data.pay_type,
            trade_id: res.data.data.trade_id
          }).then(res => {
            console.log("支付信息", res);
            if (res.data.data.type == "html") {
              pay_url.value = res.data.data.html;
              pay_dialog.value = true;
            } else if (res.data.data.type == "img") {
              pay_src.value = res.data.data.img;
            } else {
              message("支付成功", { type: "success" });
              location.reload();
              payloading.value = false;
            }
          });
        }
      });
    }
  });
};
const toNext = state => {
  if (state == 0) {
    router.push("/order/orderlist");
  }
};
//未支付
const topay_dialog = ref(true);
//镜像变量
const objectToString = obj => {
  console.log("镜像信息", obj);
  obj = JSON.parse(obj);
  if (
    obj &&
    typeof obj === "object" &&
    !Array.isArray(obj) &&
    Object.keys(obj).length > 0
  ) {
    return Object.entries(obj);
  } else {
    return "";
  }
};
//删除端口
// const delConnect = data => { };

// 添加端口价格
const payprice = ref("");
const paytitle = ref("");
const netVisible = ref(false);
const AddPort = async () => {
  netVisible.value = true;
  await getVmPortPrice({ instance_id: route.query.container_id }).then(res => {
    if (res.data.code == 200) {
      payprice.value = res.data.data.price;
    } else {
      paytitle.value = res.data.data;
    }
    console.log("端口价格", payprice.value);
  });
};
</script>

<template>
  <div class="body">
    <el-descriptions title="虚拟机信息" direction="vertical" :column="widthcolumn" size="default" border>
      <el-descriptions-item label="虚拟机 ID">{{
        container_message.id
        }}</el-descriptions-item>
      <el-descriptions-item label="价格">{{ container_message.pay }} 元</el-descriptions-item>
      <el-descriptions-item label="地区">{{ server.location }}/{{ server.name }}</el-descriptions-item>
      <el-descriptions-item label="服务器IP">{{
        server.server_ip
        }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">
        <el-tag size="small">{{ container_message.created_at }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="到期时间">
        <el-tag size="small">{{ container_message.become_time }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="所属套餐">{{
        plan.name
        }}</el-descriptions-item>
      <el-descriptions-item label="内存">{{ plan.memory }}MB</el-descriptions-item>
      <el-descriptions-item label="硬盘">{{ plan.disk }}GB<span v-if="container_message.volume_size > 0">+</span><el-tag
          v-if="container_message.volume_size > 0">{{ container_message.volume_size }}GB</el-tag></el-descriptions-item>
      <el-descriptions-item label="cpu">{{ plan.cpu }}核</el-descriptions-item>
      <el-descriptions-item label="虚拟机用户名 ">
        {{ container_message.hostname }}
      </el-descriptions-item>
      <el-descriptions-item label="虚拟机密码 ">
        <el-input v-model="password_text" type="text" style="width: 200px; height: 24px" placeholder="密码" />
        <el-button class="m-l-10px" size="small" @click="SetPassWord(container_message.id)">确认</el-button>
      </el-descriptions-item>
      <el-descriptions-item label="默认允许开放端口数" :span="1">
        {{ plan.port_num }}
      </el-descriptions-item>
      <el-descriptions-item label="镜像">{{
        image.show_name ? image.show_name : image.name
        }}</el-descriptions-item>
      <el-descriptions-item label="虚拟机IP">{{
        container_message.network_ip
        }}</el-descriptions-item>
      <el-descriptions-item label="链接端口号">{{
        Vm_link.node_port
        }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag v-if="container_message.state != '2'" :type="statusColor(container_message.state)">
          {{ statusMap(container_message.state) }}
        </el-tag>
        <el-tag v-else :type="vmStatusColor(Vm_State)">
          {{ vmStatus(Vm_State) }}
        </el-tag>
      </el-descriptions-item>

      <el-descriptions-item v-if="container_state !== 0 && container_message.pay" :span="4" label="操作">
        <SetButton :id="container_message.id" trade_type="instance" :pay="container_message.pay"
          :server_id="container_message.server_id" :state="container_message.state" :console_url="server.console_url"
          @statusUpdated="getStatus" @UpdataInfo="getInfo" />
        <el-button v-if="container_state == 0" type="primary" @click="router.push('/order/orderlist')">支付</el-button>
      </el-descriptions-item>
      <el-descriptions-item :span="8" label="镜像描述">
        <div class="mytitle">
          {{ image.description }}
        </div>
      </el-descriptions-item>
    </el-descriptions>

    <!-- tab栏 -->
    <el-tabs type="border-card" class="info_table">
      <el-tab-pane label="操作日志">
        <div>
          <el-table :data="containers_log" style="width: 100%">
            <el-table-column prop="created_at" label="时间" />
            <el-table-column prop="action_info" label="日志" />
          </el-table>
          <div class="m-t-15px">
            <el-pagination background layout="prev, pager, next,sizes" :total="logTotal" :current-page="logPagin.page"
              :page-size="logPagin.count" :page-sizes="[1, 10, 20]" @update:current-page="handleCurrentPageChange"
              @update:page-size="handlePageSizeChange" />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="实例监控" :lazy="true">
        <RunLogs :ID="container_message.id" />
      </el-tab-pane>
      <el-tab-pane label="端口管理">
        <div class="flex items-center">
          <el-button type="primary" plain @click="AddPort">添加端口</el-button>
          <div class="m-l-10px text-14px text-#8b8686eb box-orb flex items-center">
            <div class="text-14px">
              端口配额:
              <span class="text-#e72f2fcc text-17px">{{ container_connect.length }}/{{ plan.port_num }}</span>
            </div>
          </div>
        </div>

        <div class="table-container">
          <el-table class="table_el" :data="container_connect" style="width: auto">
            <el-table-column label="ID" prop="id" />
            <el-table-column label="外部访问端口" prop="node_port" />
            <el-table-column label="内部端口" prop="internal_port" />
            <el-table-column label="创建时间" prop="created_at" />
            <!-- <el-table-column label="操作">
              <template #default="scope">
                <el-row :gutter="24">
                  <el-col :span="24">
                    <el-button type="danger" plain @click="delConnect(scope.row.id)">删除</el-button>
                  </el-col>
                </el-row>
              </template>
</el-table-column> -->
          </el-table>
        </div>
      </el-tab-pane>
      <el-dialog v-model="netVisible" title="创建端口" draggable overflow>
        <div v-if="paytitle" class="m-b-10px">
          <el-alert :title="paytitle" type="error" show-icon />
        </div>
        <div style="display: flex; flex-wrap: wrap">
          <el-form ref="formRef" :model="paylist" label-width="150px">
            <el-form-item label="虚拟机内部端口号" prop="port" :rules="[
              {
                required: true,
                message: '请输入容器内部端口号',
                trigger: 'blur'
              },
              {
                validator: (rule, value, callback) => {
                  if (value < 1 || value > 65535) {
                    callback(new Error('端口号应在1-65535之间'));
                  } else {
                    callback();
                  }
                },
                trigger: 'blur'
              }
            ]">
              <el-input v-model="paylist.port" type="number" :min="1" :max="65535" placeholder="端口号应在1-65535之间" />
            </el-form-item>
            <el-form-item label="支付方式">
              <el-checkbox label="优先使用余额支付" checked disabled />
              <el-radio v-model="paylist.pay_type" :label="0" size="large">支付宝</el-radio>
              <el-radio v-model="paylist.pay_type" :label="1" size="large">微信</el-radio>
            </el-form-item>
            <el-form-item v-if="pay_src != ''" label="扫码支付">
              <el-image style="width: 100px; height: 100px" :src="pay_src" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="pay_money">
            <el-statistic title="总计结算金额：" :value="payprice == '' ? '0' + ' 元' : payprice + ' 元'" suffix="">
              <template #suffix>
                <el-icon style="vertical-align: -20px">
                  <ChatLineRound />
                </el-icon>
              </template>
            </el-statistic>
          </div>
          <div class="dialog-footer">
            <el-button @click="netVisible = false">关闭</el-button>
            <el-button type="primary" :disabled="payprice == ''" :loading="payloading" @click="topay">提交订单</el-button>
          </div>
        </template>
      </el-dialog>
      <el-tab-pane label=" 数据卷信息" :lazy="true">
        <PayVolumes :ID="container_message.id" :volumes="volumes" @GetLIst="getInfo" />
      </el-tab-pane>
      <el-tab-pane v-if="container_message.id" label="虚拟机网络管理">
        <VirtualWeb :ID="container_message.id" />
      </el-tab-pane>
      <el-tab-pane v-if="container_message.id" label="快照列表">
        <Snapshot :ID="container_message.id" :number="container_message.snapshot_num" @SetState="SetInfoState" />
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="pay_dialog" title="支付" style="width: 90%; height: 1000px">
      <iframe :srcdoc="pay_url" frameborder="0" style="width: 100%; height: 800px" />
    </el-dialog>
    <el-dialog v-if="container_state == 0" v-model="topay_dialog" title="未支付" style="width: 50%; height: 50%"
      :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <p>当前虚拟机订单未支付，请前往支付！</p>
      <a style="text-decoration: underline; color: #409eff" @click="router.push('/order/orderlist')">点击前往支付</a>
    </el-dialog>
  </div>
</template>

<style scoped>
.el-descriptions {
  margin-top: 20px;
}

.info_table {
  margin: 20px 0;
}

.table-container {
  /* 添加滚动条 */
  overflow-y: auto;
  /* 设置最大高度，超出后会出现滚动条 */
  max-height: 320px;
}

:deep(.el-col) {
  margin-top: 5px;
}

.mytitle {
  max-width: 800px;
  overflow: hidden;
  word-break: break-all;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.box-orb {
  border-radius: 20px;
  font-weight: 700;
  border: 1px solid #d8ebff;
  background: #ebf5ff;
  padding: 0px 8px;
}
</style>
